<?php

namespace app\admin\controller;

use app\admin\model\Advert;
use think\Controller;
use think\Db;
use think\Request;

class Adverts extends Controller
{
    public function index()
    {
        $adverts = Db::table('advertisements')
            ->alias('a')
            ->leftJoin('advertisement_nodes n', 'a.advertisement_node_id = n.id')
            ->leftJoin('photos p', 'a.photo_id = p.id')
            ->field('a.*,n.name

 as node_name,p.image')
            ->paginate(5);
//       $adverts =  Db::table('advertisements')
//            ->alias('a')
//            ->leftjoin('advertisement_nodes w','a.advertisement_node_id = w.id')
//            ->leftjoin('photos c','a.photo_id = c.id')->field('a.*,w.name as node_name
//            ,c.image')
//            ->paginate(5);
//       return $adverts;
        return view('Adverts/index', compact('adverts'));
    }

    public function create()
    {
        $nodes = Db::table('advertisement_nodes')->select();
//        return $nodes;


        return view('Adverts/create', compact('nodes'));
    }

    public function save(Request $request)
    {


//        $data = [
//            'advertisement_node_id' => $request->param('advertisement_node_id'),
//            'photo_id' => $request->param('photo_id'),
//            'name' => $request->param('name'),
//            'url' => $request->param('url'),
//            'desc' => $request->param('desc'),
//            'sort' => $request->param('sort'),
//            'create_time' => time(),
//            'update_time' => time(),
//        ];

        $data = $request->param();
        $data['create_time'] = date('Y-m-d H:i:s', time());
        $data['update_time'] = date('Y-m-d H:i:s', time());

//        return $data;
        Db::name('advertisements')->insert($data);
        return redirect('Adverts/index');

    }

    public function edit($id)
    {
        $nodes = Db::table('advertisement_nodes')->select();
        $advert = Db::table('advertisements')
            ->alias('a')
            ->leftJoin('advertisement_nodes n', 'a.advertisement_node_id = n.id')
            ->leftJoin('photos p', 'a.photo_id = p.id')
            ->field('a.*,n.name

 as node_name,p.image')->where("a.id = '$id'")
            ->find();
//        return $advert;
        return view('Adverts/edit', compact('nodes', 'advert'));
    }

    public function update(Request $request, $id)
    {

        $data = $request->param();

        Db::name('advertisements')
            ->where("id = '$id'")
            ->data($data)
            ->update();
        return redirect('Adverts/index');
    }

    public function delete($id)
    {
        Db::table('advertisements')->where("id = '$id'")->delete();
        return redirect('Adverts/index');
    }

}